# -*- coding: utf-8 -*-
"""
用户会话模型
@api-version: 1.0.0
"""

from datetime import datetime, timedelta
from . import db
import secrets

class UserSession(db.Model):
    """用户会话模型"""
    __tablename__ = 'user_sessions'
    
    id = db.Column(db.Integer, primary_key=True, comment='会话ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, comment='用户ID')
    token = db.Column(db.String(255), unique=True, nullable=False, comment='访问令牌')
    refresh_token = db.Column(db.String(255), unique=True, nullable=False, comment='刷新令牌')
    expires_at = db.Column(db.DateTime, nullable=False, comment='过期时间')
    ip_address = db.Column(db.String(45), comment='IP地址')
    user_agent = db.Column(db.Text, comment='用户代理')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, 
                          onupdate=datetime.utcnow, comment='更新时间')
    
    def __init__(self, user_id, ip_address=None, user_agent=None, expires_hours=24):
        self.user_id = user_id
        self.token = self.generate_token()
        self.refresh_token = self.generate_token()
        self.expires_at = datetime.utcnow() + timedelta(hours=expires_hours)
        self.ip_address = ip_address
        self.user_agent = user_agent
    
    @staticmethod
    def generate_token():
        """生成随机令牌"""
        return secrets.token_urlsafe(32)
    
    def is_expired(self):
        """检查是否过期"""
        return datetime.utcnow() > self.expires_at
    
    def refresh(self, expires_hours=24):
        """刷新会话"""
        self.token = self.generate_token()
        self.refresh_token = self.generate_token()
        self.expires_at = datetime.utcnow() + timedelta(hours=expires_hours)
        self.updated_at = datetime.utcnow()
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'userId': self.user_id,
            'token': self.token,
            'refreshToken': self.refresh_token,
            'expiresAt': self.expires_at.isoformat() if self.expires_at else None,
            'ipAddress': self.ip_address,
            'userAgent': self.user_agent,
            'createdAt': self.created_at.isoformat() if self.created_at else None,
            'updatedAt': self.updated_at.isoformat() if self.updated_at else None
        }
    
    @classmethod
    def cleanup_expired(cls):
        """清理过期会话"""
        expired_sessions = cls.query.filter(cls.expires_at < datetime.utcnow()).all()
        for session in expired_sessions:
            db.session.delete(session)
        db.session.commit()
        return len(expired_sessions)
    
    def __repr__(self):
        return f'<UserSession {self.id} for User {self.user_id}>'